package com.webemail.sys.controller;

import com.alibaba.fastjson2.JSON;
import com.webemail.sys.model.*;
import com.webemail.sys.service.*;
import com.webemail.sys.util.*;
import com.webemail.sys.util.MailConnect.FolderType;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@Slf4j
public class EmailController {
	@Resource
	private EmailService emailService;
	@Resource
	private FolderService folderService;
	@Resource
	private LabelMessageService labelMessageService;
	@Resource
	private LabelService labelService;
	@Resource
	private MessageDeletedService messageDeletedService;
	@Resource
	private MessageDraftsService messageDraftsService;
	@Resource
	private MessageFolderService messageFolderService;
	@Resource
	private MessageInboxService messageInboxService;
	@Resource
	private MessageSendService messageSendService;

	private static String saveURL = "http://localhost:8080/mail";
	private static String saveFolder = "uploadFiles";

	private long getUserId() {
		return 1L;
	}

	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String filePath = request.getSession().getServletContext().getRealPath("imgupload/" + this.getUserId() + "/");
		try {
			CommonUtils.saveFile(file.getBytes(), filePath, uuid + fileType);
		} catch (Exception e) {
			return JSON.toJSONString(new LayuiUploadBean(1, "上传失败", "", ""));
		}
		return JSON.toJSONString(new LayuiUploadBean(0, "上传成功",
				saveURL + "/imgupload/" + this.getUserId() + "/" + uuid + fileType, fileName));
	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public @ResponseBody String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String fileName = file.getOriginalFilename();
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String filePath = request.getSession().getServletContext()
				.getRealPath("uploadFile/" + this.getUserId() + "/" + uuid + "/");
		try {
			CommonUtils.saveFile(file.getBytes(), filePath, fileName);
		} catch (Exception e) {
			return JSON.toJSONString(new LayuiUploadBean(1, "上传失败", "", ""));
		}
		return JSON.toJSONString(new LayuiUploadBean(0, "上传成功",
				saveURL + "/uploadFile/" + this.getUserId() + "/" + uuid + "/" + fileName, fileName));
	}

	@RequestMapping("/sendEmail")
	@ResponseBody
	public String sendEmail(HttpServletRequest request, Model model) {
		long userId = this.getUserId();
		String sendmail = CommonUtils.getString(request.getParameter("sendmail"));
		int mailId = Integer.parseInt(sendmail);
		String remail = CommonUtils.getString(request.getParameter("remail"));
		String copyto = CommonUtils.getString(request.getParameter("copyto"));
		String bcopyto = CommonUtils.getString(request.getParameter("bcopyto"));
		String subject = CommonUtils.getString(request.getParameter("subject"));
		String bodytext = CommonUtils.getString(request.getParameter("bodytext"));
		boolean priority = CommonUtils.getString(request.getParameter("priority")).equalsIgnoreCase("true");
		boolean notification = CommonUtils.getString(request.getParameter("notification")).equalsIgnoreCase("true");
		String file[] = request.getParameterValues("file[]");
		String filePath = request.getSession().getServletContext().getRealPath("uploadFile/");
		if (file != null) {
			for (int i = 0; i < file.length; i++) {
				System.out.println("1:" + file[i]);
				System.out.println("2:" + filePath.substring(0, filePath.length() - 1));
				System.out.println("3:" + saveURL);
				System.out.println("4:" + file[i].substring((saveURL + "/uploadFile").length()));
				file[i] = filePath.substring(0, filePath.length() - 1)
						+ file[i].substring((saveURL + "/uploadFile/").length() - 1);
				System.out.println("5:" + file[i]);
			}
		}
		SysEmailAccount sysEmailAccount = emailService.get(mailId, userId);
		MailBean mailBean = MailUtils.getSendMailBean(sysEmailAccount);
		MailSender sender = new MailSender(mailBean);
		MimeMessage mimeMessage = sender.SendEmail(remail, copyto, bcopyto, subject, bodytext, file, priority,
				notification);
		// MailContent mailContent=new MailContent(mimeMessage);
		SysMessageSend result = new SysMessageSend();
		result.setUserId((long) userId);
		result.setMailId((long) mailId);
		result.setFolder("发件箱");
		result.setFolderId((long) 0);
		result.setSubject(subject);
		result.setBodyText(bodytext);
		try {
			result.setMessageId(mimeMessage.getMessageID());
			result.setSentDate(CommonUtils.getDateStr(mimeMessage.getSentDate()));
			result.setSentDateTime(String.valueOf(mimeMessage.getSentDate().getTime()));
			result.setSize((long) mimeMessage.getSize());
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		result.setMailFrom(mailBean.getAccount());
		result.setMailAddress(remail);
		result.setMailCopyto(copyto);
		result.setMailBCopyto(bcopyto);
		if (file != null && file.length > 0) {
			result.setHasAttachment("true");
		} else {
			result.setHasAttachment("false");
		}
		String fileUrls[] = request.getParameterValues("file[]");
		if (ObjectUtil.isNotEmpty(result.getAttachment()) && fileUrls != null && fileUrls.length > 0) {
			result.setAttachment(StringUtils.join(fileUrls, ","));
		}
		result.setHasRead("true");
		result.setIsDefaultFolder("true");
		result.setHasReply("false");
		result.setLabel("");
		result.setSource(true);
		result.setState((long) 0);
		messageSendService.insert(result);
		if (sender.getState() == 0) {
			return JSON.toJSONString(new ResultBean(1, "发送成功"));
		} else {
			return JSON.toJSONString(new ResultBean(0, sender.getErrorMsg()));
		}
	}

	@RequestMapping("/saveDrafts")
	@ResponseBody
	public String saveDrafts(HttpServletRequest request, Model model) {
		long userId = this.getUserId();
		String sendmail = CommonUtils.getString(request.getParameter("sendmail"));
		int mailId = Integer.parseInt(sendmail);
		String remail = CommonUtils.getString(request.getParameter("remail"));
		String copyto = CommonUtils.getString(request.getParameter("copyto"));
		String bcopyto = CommonUtils.getString(request.getParameter("bcopyto"));
		String subject = CommonUtils.getString(request.getParameter("subject"));
		String bodytext = CommonUtils.getString(request.getParameter("bodytext"));
		boolean priority = CommonUtils.getString(request.getParameter("priority")).equalsIgnoreCase("true");
		boolean notification = CommonUtils.getString(request.getParameter("notification")).equalsIgnoreCase("true");
		SysEmailAccount sysEmailAccount = emailService.get(mailId, userId);
		SysMessageDrafts bean = new SysMessageDrafts();
		bean.setUserId((long) userId);
		bean.setMailId((long) mailId);
		bean.setFolder("草稿箱");
		bean.setFolderId((long) 0);
		bean.setSubject(subject);
		bean.setBodyText(bodytext);
		bean.setMailFrom(sysEmailAccount.getAccount());
		bean.setMailAddress(remail);
		bean.setMailCopyto(copyto);
		bean.setMailBCopyto(bcopyto);
		String file[] = request.getParameterValues("file[]");
		if (file != null && file.length > 0) {
			bean.setHasAttachment("true");
			bean.setAttachment(StringUtils.join(file, ","));
		} else {
			bean.setHasAttachment("false");
		}
		bean.setHasRead("true");
		bean.setIsDefaultFolder("true");
		bean.setHasReply("false");
		bean.setLabel("");
		bean.setSource(true);
		if (priority) {
			bean.setPriority("true");
		} else {
			bean.setPriority("false");
		}
		if (notification) {
			bean.setNotification("true");
		} else {
			bean.setNotification("false");
		}
		bean.setState((long) 0);
		if (messageDraftsService.insert(bean) >= 0) {
			return JSON.toJSONString(new ResultBean(1, "保存成功"));
		} else {
			return JSON.toJSONString(new ResultBean(0, "保存失败"));
		}
	}

	/*
	 * @RequestMapping("/emailReplyDo")
	 * 
	 * @ResponseBody public String emailReplyDo(HttpServletRequest request,
	 * Model model) { long userId = this.getUserId(); String messageId =
	 * CommonUtils.getString(request.getParameter("messageId"));//邮件id String
	 * mailType = CommonUtils.getString(request.getParameter("mailType"));//邮件来源
	 * String sendmail =
	 * CommonUtils.getString(request.getParameter("sendmail"));//发送邮件id String
	 * remail = CommonUtils.getString(request.getParameter("remail"));//收件人
	 * String copyto =
	 * CommonUtils.getString(request.getParameter("copyto"));//抄送 String bcopyto
	 * = CommonUtils.getString(request.getParameter("bcopyto"));//密送 String
	 * subject = CommonUtils.getString(request.getParameter("subject"));//主题
	 * String bodytext =
	 * CommonUtils.getString(request.getParameter("bodytext"));//内容 boolean
	 * priority =
	 * CommonUtils.getString(request.getParameter("priority")).equalsIgnoreCase(
	 * "true"); boolean notification =
	 * CommonUtils.getString(request.getParameter("notification")).
	 * equalsIgnoreCase("true"); int mailId = Integer.parseInt(sendmail);//
	 * String file[] = request.getParameterValues("file[]"); String filePath =
	 * request.getSession().getServletContext().getRealPath("uploadFile/"); if
	 * (file != null) { for (int i = 0; i < file.length; i++) {
	 * System.out.println("1:"+file[i]); System.out.println("2:"+
	 * filePath.substring(0, filePath.length() - 1)); System.out.println("3:"+
	 * saveURL); System.out.println("4:"+ file[i].substring((saveURL +
	 * "/uploadFile").length())); file[i] = filePath.substring(0,
	 * filePath.length() - 1)+ file[i].substring((saveURL +
	 * "/uploadFile/").length() - 1); System.out.println("5:"+file[i]); } }
	 * SysEmail sysEmail = emailService.get(mailId, userId); if(sysEmail==null){
	 * return JSON.toJSONString(new ResultBean(0, "发送失败")); } MailBean mailBean
	 * = MailUtils.getReMailBean(sysEmail); if(mailBean==null){ return
	 * JSON.toJSONString(new ResultBean(0, "发送失败")); } MailConnect mailConnect =
	 * new MailConnect(mailBean); mailConnect.init(); if (mailConnect.getState()
	 * != 0) { return JSON.toJSONString(new ResultBean(0, "发送失败")); } Long
	 * tempId = null; try { tempId = Long.parseLong(messageId); } catch
	 * (Exception e) { e.printStackTrace(); return JSON.toJSONString(new
	 * ResultBean(0, "发送失败")); } if (mailType.equalsIgnoreCase("INBOX")) {
	 * Folder folder=mailConnect.getINFolder(); MailFolder mailFolder = new
	 * MailFolder(folder); ArrayList<MailContent> mailContent =
	 * mailFolder.getMailContent(); SysMessageInbox temp =
	 * messageInboxService.get(tempId, userId); for (int i = 0; i <
	 * mailContent.size(); i++) { MailContent mailContentObject =
	 * mailContent.get(i); if
	 * (mailContentObject.getMessageId().trim().equalsIgnoreCase(temp.
	 * getMessageId().trim())&&
	 * temp.getSentDateTime().equals(String.valueOf(mailContentObject.
	 * getSentDate().getTime()))) { MailBean sendMailBean =
	 * MailUtils.getSendMailBean(sysEmail); MailSender sender = new
	 * MailSender(sendMailBean); MimeMessage
	 * mimeMessage=sender.replyMail(mailContentObject.getMessage(), remail,
	 * copyto, bcopyto, subject, bodytext, file, priority, notification, false);
	 * SysMessageSend result = new SysMessageSend(); result.setUserId((long)
	 * userId); result.setMailId((long) mailId); result.setFolder("发件箱");
	 * result.setFolderId((long) 0); result.setSubject(subject);
	 * result.setBodyText(bodytext); try {
	 * result.setMessageId(mimeMessage.getMessageID());
	 * result.setSentDate(CommonUtils.getDateStr(mimeMessage.getSentDate()));
	 * result.setSentDateTime(String.valueOf(mimeMessage.getSentDate().getTime()
	 * )); result.setSize((long) mimeMessage.getSize()); } catch
	 * (MessagingException e) { e.printStackTrace(); }
	 * result.setMailFrom(mailBean.getAccount()); result.setMailAddress(remail);
	 * result.setMailCopyto(copyto); result.setMailBCopyto(bcopyto);
	 * 
	 * if (file != null && file.length > 0) { result.setHasAttachment("true"); }
	 * else { result.setHasAttachment("false"); } String fileUrls[] =
	 * request.getParameterValues("file[]"); if (result.hasAttachment() &&
	 * fileUrls != null && fileUrls.length > 0) {
	 * result.setAttachment(StringUtils.join(fileUrls, ",")); }
	 * result.setHasRead("true"); result.setIsDefaultFolder("true");
	 * result.setHasReply("true"); result.setLabel(""); result.setSource(true);
	 * result.setState((long) 0); messageSendService.insert(result); break; } }
	 * mailConnect.stop(); } return JSON.toJSONString(new ResultBean(0,
	 * "发送成功")); }
	 */

	/////////////////////////////////////
	@RequestMapping("/emailRead")
	@ResponseBody
	public String emailRead(HttpServletRequest request, Model model) {
		String messageIds = CommonUtils.getString(request.getParameter("messageIds"));
		int read = Integer.parseInt(CommonUtils.getString(request.getParameter("read")));
		if (this.readMessage(messageIds, read, FolderType.INFolder)) {
			return JSON.toJSONString(new ResultBean(1, "修改成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "修改失败", null));
		}
	}

	/**
	 * 
	 * @param messageIds
	 * @param read
	 * @param folderType
	 * @return
	 */
	private boolean readMessage(String messageIds, int read, FolderType folderType) {
		long userId = this.getUserId();
		String messageId[] = messageIds.split(",");
		SysEmailAccount sysEmailAccount = null;
		MailConnect mailConnect = null;
		int count = 0;
		for (int i = 0; i < messageId.length; i++) {
			long tempId = Long.parseLong(messageId[i]);
			SysMessageInbox message = messageInboxService.get(tempId, userId);
			if (read == 0) {
				message.setHasRead("false");
			} else {
				message.setHasRead("true");
			}
			int result = messageInboxService.update(message);
			if (sysEmailAccount == null) {
				long mailId = message.getMailId();
				sysEmailAccount = emailService.get(mailId, userId);
				mailConnect = new MailConnect(MailUtils.getReMailBean(sysEmailAccount));
				// mailConnect.checkProperties();
				mailConnect.init();
				if (mailConnect.getState() != 0) {
					sysEmailAccount.setIsSubmit("false");
				}
			}
			if (sysEmailAccount != null) {
				if (sysEmailAccount.isSubmit()) {
					if (read == 0) {
						mailConnect.unReadMessage(folderType, message.getMessageId(), message.getSentDateTime());
					} else {
						mailConnect.readMessage(folderType, message.getMessageId(), message.getSentDateTime());
					}
				}
			}
			if (result > 0) {
				count++;
			}
		}
		if (mailConnect != null) {
			mailConnect.stop();
		}
		if (count == messageId.length) {
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping("/emailDelete")
	@ResponseBody
	public String emailDelete(HttpServletRequest request, Model model) {
		String[] messageIds = null;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1) {
			return JSON.toJSONString(new ResultBean(0, "删除失败", null));
		}

		for (int i = 0; i < messageIds.length; i++) {
			try {
				// TODO
				long messageId = Long.parseLong(messageIds[i].trim());
				SysMessageInbox message = messageInboxService.get(messageId, userId);
				if (message != null && message.getId() > 0) {
					message.setState((long) 1);
					SysMessageDeleted temp = new SysMessageDeleted();
					temp.setUserId(message.getUserId());
					temp.setMailId(message.getMailId());
					temp.setFolder("已删除");
					temp.setFolderId((long) 0);
					temp.setMessageId(message.getMessageId());
					temp.setSubject(message.getSubject());
					temp.setBodyText(message.getBodyText());
					temp.setSentDate(message.getSentDate());
					temp.setSentDateTime(message.getSentDateTime());
					temp.setSize(message.getSize());
					temp.setMailFrom(message.getMailFrom());
					temp.setMailAddress(message.getMailAddress());
					temp.setMailCopyto(message.getMailCopyto());
					temp.setMailBCopyto(message.getMailBCopyto());
					temp.setHasAttachment(message.getHasAttachment());
					temp.setAttachment(message.getAttachment());
					temp.setHasRead(message.getHasRead());
					temp.setIsDefaultFolder(message.getIsDefaultFolder());
					temp.setHasReply(message.getHasReply());
					temp.setLabel(message.getLabel());
					temp.setSource(message.isLocalSource());
					temp.setState((long) 0);
					messageDeletedService.insert(temp);
					if (messageInboxService.update(message) > 0) {
						succIds.add(message.getId());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "删除成功", succIds));
		} else {

		}
		return JSON.toJSONString(new ResultBean(0, "删除失败", succIds));
	}

	@RequestMapping("/emailDeleteAll")
	@ResponseBody
	public String emailDeleteAll(HttpServletRequest request, Model model) {

		String[] messageIds = null;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1) {
			return JSON.toJSONString(new ResultBean(0, "删除失败", null));
		}
		SysEmailAccount sysEmailAccount = null;
		MailConnect mailConnect = null;
		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i].trim());
				SysMessageInbox message = messageInboxService.get(messageId, userId);
				if (message != null && message.getId() > 0) {
					message.setState((long) 1);
					// 添加到删除
					SysMessageDeleted temp = new SysMessageDeleted();
					temp.setUserId(message.getUserId());
					temp.setMailId(message.getMailId());
					temp.setFolder("已删除");
					temp.setFolderId((long) 0);
					temp.setMessageId(message.getMessageId());
					temp.setSubject(message.getSubject());
					temp.setBodyText(message.getBodyText());
					temp.setSentDate(message.getSentDate());
					temp.setSentDateTime(message.getSentDateTime());
					temp.setSize(message.getSize());
					temp.setMailFrom(message.getMailFrom());
					temp.setMailAddress(message.getMailAddress());
					temp.setMailCopyto(message.getMailCopyto());
					temp.setMailBCopyto(message.getMailBCopyto());
					temp.setHasAttachment(message.getHasAttachment());
					temp.setAttachment(message.getAttachment());
					temp.setHasRead(message.getHasRead());
					temp.setIsDefaultFolder(message.getIsDefaultFolder());
					temp.setHasReply(message.getHasReply());
					temp.setLabel(message.getLabel());
					temp.setSource(message.isLocalSource());
					temp.setState((long) 0);
					messageDeletedService.insert(temp);
					//
					if (messageInboxService.update(message) > 0) {
						succIds.add(message.getId());
						if (sysEmailAccount == null) {
							sysEmailAccount = emailService.get(message.getMailId(), userId);
						}
						if (mailConnect == null && sysEmailAccount != null && sysEmailAccount.getId() > 0) {
							mailConnect = new MailConnect(MailUtils.getReMailBean(sysEmailAccount));
							mailConnect.init();
						}
						if (mailConnect != null) {
							mailConnect.deleteMessage(FolderType.INFolder, message.getMessageId(),
									message.getSentDateTime());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (mailConnect != null) {
			mailConnect.stop();
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "删除成功", succIds));
		} else {

		}
		return JSON.toJSONString(new ResultBean(0, "删除失败", succIds));
	}

	@RequestMapping("/emailMoveFolder")
	@ResponseBody
	public String emailMoveFolder(HttpServletRequest request, Model model) {

		String[] messageIds = null;
		long folderId = 0;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
			folderId = Long.parseLong(CommonUtils.getString(request.getParameter("folderId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1 || folderId < 1) {
			return JSON.toJSONString(new ResultBean(0, "移动失败", null));
		}
		SysFolder folder = folderService.get(folderId, userId);
		if (folder == null || folder.getId() < 1) {
			return JSON.toJSONString(new ResultBean(0, "文件夹不存在", null));
		}

		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i]);
				SysMessageInbox message = messageInboxService.get(messageId, userId);
				SysMessageFolder messageFolder = new SysMessageFolder();
				messageFolder.setUserId(userId);
				messageFolder.setMailId(message.getMailId());
				messageFolder.setFolder(folder.getName());
				messageFolder.setFolderId(folder.getId());
				messageFolder.setMessageId(message.getMessageId());
				messageFolder.setSubject(message.getSubject());
				messageFolder.setBodyText(message.getBodyText());
				messageFolder.setSentDate(message.getSentDate());
				messageFolder.setSentDateTime(message.getSentDateTime());
				messageFolder.setSize(message.getSize());
				messageFolder.setMailFrom(message.getMailFrom());
				messageFolder.setMailAddress(message.getMailAddress());
				messageFolder.setMailCopyto(message.getMailCopyto());
				messageFolder.setMailBCopyto(message.getMailBCopyto());
				messageFolder.setHasAttachment(message.getHasAttachment());
				messageFolder.setAttachment(message.getAttachment());
				messageFolder.setHasRead(message.getHasRead());
				messageFolder.setIsDefaultFolder("false");
				messageFolder.setHasReply(message.getHasReply());
				messageFolder.setLabel(message.getLabel());
				messageFolder.setSource(message.isLocalSource());
				messageFolder.setState((long) 0);
				messageFolderService.insert(messageFolder);
				message.setState((long) 3);
				messageInboxService.update(message);
				succIds.add(message.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "移动成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "移动失败", null));
		}
	}

	@RequestMapping("/emailAddLabel")
	@ResponseBody
	public String emailAddLabel(HttpServletRequest request, Model model) {
		String[] messageIds = null;
		long labelId = 0;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
			labelId = Long.parseLong(CommonUtils.getString(request.getParameter("labelId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1 || labelId < 1) {
			return JSON.toJSONString(new ResultBean(0, "添加失败", null));
		}
		SysLabel label = labelService.get(labelId, userId);
		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i]);
				SysMessageInbox message = messageInboxService.get(messageId, userId);
				SysLabelMessage labelMessage = labelMessageService.get(userId, label.getId() + "", message.getId() + "",
						"收件箱");
				if (labelMessage == null || labelMessage.getId() < 1) {
					labelMessage = new SysLabelMessage();
					labelMessage.setLabelId(label.getId() + "");
					labelMessage.setMessageId(message.getId() + "");
					labelMessage.setTable("收件箱");
					labelMessage.setUserId(userId);
					labelMessageService.insert(labelMessage);
				}
				if (!CommonUtils.getString(message.getLabel()).contains(label.getName().trim())) {
					if (StringUtils.isBlank(message.getLabel())) {
						message.setLabel(label.getName());
					} else {
						message.setLabel(message.getLabel() + "," + label.getName());
					}
					messageInboxService.update(message);
				}
				succIds.add(message.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "添加成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "添加失败", null));
		}
	}

	@RequestMapping("/emailRemoveLabel")
	@ResponseBody
	public String emailRemoveLabel(HttpServletRequest request, Model model) {
		long messageId = 0;
		String labelName = "";
		long userId = this.getUserId();
		try {
			messageId = Long.parseLong(CommonUtils.getString(request.getParameter("messageId")));
			labelName = CommonUtils.getString(request.getParameter("labelName"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageId < 1 || StringUtils.isBlank(labelName)) {
			return JSON.toJSONString(new ResultBean(0, "移除失败", null));
		}
		SysLabel label = labelService.get(userId, labelName);
		if (label == null || label.getId() < 1) {
			return JSON.toJSONString(new ResultBean(0, "标签不存在", null));
		}
		try {
			SysMessageInbox message = messageInboxService.get(messageId, userId);
			SysLabelMessage labelMessage = labelMessageService.get(userId, label.getId() + "", message.getId() + "",
					"收件箱");
			if (labelMessage != null && labelMessage.getId() > 0) {
				labelMessageService.delete(labelMessage.getId(), userId);
			}
			if (CommonUtils.getString(message.getLabel()).contains(label.getName().trim())) {
				String[] labels = message.getLabel().trim().split(",");
				ArrayList<String> labelList = new ArrayList<String>();
				for (int i = 0; i < labels.length; i++) {
					if (!labels[i].trim().equalsIgnoreCase(label.getName().trim())) {
						labelList.add(labels[i].trim());
					}
				}
				message.setLabel(StringUtils.join(labelList, ","));
				messageInboxService.update(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, "移除失败", null));
		}
		return JSON.toJSONString(new ResultBean(1, "移除成功", null));
	}

	@RequestMapping("/emailReviceALLPage")
	@ResponseBody
	public String emailReviceALLPage(HttpServletRequest request, Model model) {
		String colomn = CommonUtils.getString(request.getParameter("colomn"));
		String word = CommonUtils.getString(request.getParameter("word"));

		long userId = this.getUserId();
		int page = 0;
		int limit = 10;
		LayuiBean<SysMessageInbox> layuiBean;
		try {
			page = Integer.parseInt(CommonUtils.getString(request.getParameter("page")));
		} catch (Exception e) {
			e.printStackTrace();
			page = 0;
		}
		if (page > 0) {
			page--;
		}
		try {
			limit = Integer.parseInt(CommonUtils.getString(request.getParameter("limit")));
		} catch (Exception e) {
			e.printStackTrace();
			limit = 10;
		}

		List<SysMessageInbox> result = messageInboxService.listByPage(userId, colomn, word, page * limit, limit, 0, 2);
		Long size = messageInboxService.count(userId, colomn, word, 0, 2);
		layuiBean = new LayuiBean<SysMessageInbox>(0, "SUCC", size, result);
		return JSON.toJSONString(layuiBean);
	}

	@RequestMapping("/refreshInboxAll")
	@ResponseBody
	public String refreshInboxAll(HttpServletRequest request, Model model) {
		String path = request.getSession().getServletContext().getRealPath("/");
		long userId = this.getUserId();
		List<SysEmailAccount> mails;
		try {
			mails = emailService.list(userId);
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, e.getMessage(), null));
		}
		if (mails == null || mails.size() < 1) {
			return JSON.toJSONString(new ResultBean(0, "没有添加邮箱", null));
		}
		for (int key = 0; key < mails.size(); key++) {
			SysEmailAccount temp = mails.get(key);
			long mailId = temp.getId();
			try {
				MailBean re;
				MailConnect mailConnect;
				try {
					re = MailUtils.getLsReMailBean(temp);
					mailConnect = new MailConnect(re);
					mailConnect.checkProperties();
				} catch (Exception e) {
					e.printStackTrace();
					return JSON.toJSONString(new ResultBean(0, e.getMessage(), null));
				}
				if (mailConnect.getState() != 0) {
					return JSON.toJSONString(new ResultBean(0, mailConnect.getErrorMsg(), null));
				}
				mailConnect.init();

				Folder folder = mailConnect.getINFolder();
				MailFolder mailFolder = new MailFolder(folder);
				ArrayList<MailContent> mailContentList = mailFolder.getMailContent();
				List<SysMessageInbox> messageInboxs = messageInboxService.list(mailId, userId);
				ArrayList<SysMessageInbox> sysMessageInboxList = new ArrayList<>();
				for (int i = 0; i < mailContentList.size(); i++) {
					MailContent mailContentObject = mailContentList.get(i);
					boolean flag = true;
					for (int j = 0; j < messageInboxs.size(); j++) {
						SysMessageInbox messageInboxsObj = messageInboxs.get(j);
						if (mailContentObject.getMessageId().trim()
								.equalsIgnoreCase(messageInboxsObj.getMessageId().trim())
								&& messageInboxsObj.getSentDateTime()
										.equals(String.valueOf(mailContentObject.getSentDate().getTime()))) {
							flag = false;
							break;
						}
					}
					if (flag) {
						// 保存邮件
						sysMessageInboxList.add(
								this.toSysMessageInbox(mailContentObject, userId, mailId, "收件箱", true, 0, true, path));
					}
				}
				mailConnect.stop();
				if (sysMessageInboxList.size() > 0) {
					messageInboxService.insert(sysMessageInboxList);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return JSON.toJSONString(new ResultBean(1, "刷新成功", null));
	}


	@RequestMapping("/refreshInbox")
	@ResponseBody
	public String refreshInbox(HttpServletRequest request, Model model) {
		String path = request.getSession().getServletContext().getRealPath("/");
		long userId = this.getUserId();
		long mailId = 0;
		SysEmailAccount temp = null;
		try {
			String id = CommonUtils.getString(request.getParameter("id"));
			mailId = Long.parseLong(id);
			temp = emailService.get(mailId, this.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, e.getMessage(), null));
		}
		MailBean re = null;
		MailConnect mailConnect = null;
		try {
			re = MailUtils.getReMailBean(temp);
			mailConnect = new MailConnect(re);
			mailConnect.checkProperties();
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, e.getMessage(), null));
		}
		if (mailConnect.getState() != 0) {
			return JSON.toJSONString(new ResultBean(0, mailConnect.getErrorMsg(), null));
		}
		mailConnect.init();
		Folder folder = mailConnect.getINFolder();
		MailFolder mailFolder = new MailFolder(folder);
		ArrayList<MailContent> mailContentList = mailFolder.getMailContent();
		List<SysMessageInbox> messageInboxs = messageInboxService.list(mailId, userId);
		ArrayList<SysMessageInbox> addMessageList = new ArrayList<SysMessageInbox>();
		for (int i = 0; i < mailContentList.size(); i++) {
			MailContent mailContentObject = mailContentList.get(i);
			boolean flag = true;
			for (int j = 0; j < messageInboxs.size(); j++) {
				SysMessageInbox messageInboxsObj = messageInboxs.get(j);
				if ((mailContentObject.getMessageId()!=null&&messageInboxsObj.getMessageId()!=null&&mailContentObject.getMessageId().trim().equalsIgnoreCase(messageInboxsObj.getMessageId().trim()))
						|| (mailContentObject.getSentDate()!=null&&messageInboxsObj.getSentDateTime().equals(String.valueOf(mailContentObject.getSentDate().getTime())))) {
					flag = false;
					break;
				}
			}
			if (flag) {
				// 保存邮件
				addMessageList.add(this.toSysMessageInbox(mailContentObject, userId, mailId, "收件箱", true, 0, true, path));
			}
		}
		mailConnect.stop();
		if (addMessageList.size() > 0) {
			messageInboxService.insert(addMessageList);
		}
		return JSON.toJSONString(new ResultBean(1, "刷新成功", null));
	}

	@RequestMapping("/emailRevicePage")
	@ResponseBody
	public String emailRevicePage(HttpServletRequest request, Model model) {
		String colomn = CommonUtils.getString(request.getParameter("colomn"));
		String word = CommonUtils.getString(request.getParameter("word"));
		long userId = this.getUserId();
		long mailId = 0;
		int page = 0;
		int limit = 10;
		LayuiBean<SysMessageInbox> layuiBean;
		try {
			page = Integer.parseInt(CommonUtils.getString(request.getParameter("page")));
		} catch (Exception e) {
			e.printStackTrace();
			page = 0;
		}
		if (page > 0) {
			page--;
		}
		try {
			limit = Integer.parseInt(CommonUtils.getString(request.getParameter("limit")));
		} catch (Exception e) {
			e.printStackTrace();
			limit = 10;
		}
		try {
			mailId = Long.parseLong(CommonUtils.getString(request.getParameter("mailId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<SysMessageInbox> result = messageInboxService.listByPage(userId, mailId, colomn, word, page * limit, limit,
				0, 2);
		long size = messageInboxService.count(userId, mailId, colomn, word, 0, 2);
		layuiBean = new LayuiBean<SysMessageInbox>(0, "SUCC", size, result);
		return JSON.toJSONString(layuiBean);
	}

	@RequestMapping("/labelAll")
	@ResponseBody
	public String labelAll(HttpServletRequest request, Model model) {
		List<SysLabel> list = labelService.list(this.getUserId());
		LayuiBean<SysLabel> l = new LayuiBean<SysLabel>(0, "SUCC", list.size(), list);
		return JSON.toJSONString(l);
	}

	@RequestMapping("/folderAll")
	@ResponseBody
	public String folderAll(HttpServletRequest request, Model model) {
		List<SysFolder> list = folderService.list(this.getUserId());
		LayuiBean<SysFolder> l = new LayuiBean<SysFolder>(0, "SUCC", list.size(), list);
		return JSON.toJSONString(l);
	}

	@RequestMapping("/emailAll")
	@ResponseBody
	public String emailAll(HttpServletRequest request, Model model) {
		List<SysEmailAccount> list = emailService.list(this.getUserId());
		LayuiBean<SysEmailAccount> l = new LayuiBean<SysEmailAccount>(0, "SUCC", list.size(), list);
		return JSON.toJSONString(l);
	}

	@RequestMapping("/labelAddDo")
	@ResponseBody
	public String labelAddDo(HttpServletRequest request, Model model) {
		String name = CommonUtils.getString(request.getParameter("name"));
		if (StringUtils.isBlank(name)) {
			return JSON.toJSONString(new ResultBean(0, "没有标签名称"));
		}
		SysLabel sysLabel = new SysLabel();
		sysLabel.setName(name);
		sysLabel.setUserId((long) this.getUserId());
		if (labelService.insert(sysLabel) > 0) {
			return JSON.toJSONString(new ResultBean(1, "添加成功"));
		} else {
			return JSON.toJSONString(new ResultBean(1, "添加失败"));
		}
	}

	@RequestMapping("/folderAddDo")
	@ResponseBody
	public String folderAddDo(HttpServletRequest request, Model model) {
		String name = CommonUtils.getString(request.getParameter("name"));
		if (StringUtils.isBlank(name)) {
			return JSON.toJSONString(new ResultBean(0, "没有文件夹名称"));
		}
		SysFolder sysFolder = new SysFolder();
		sysFolder.setName(name);
		sysFolder.setUserId((long) this.getUserId());
		if (folderService.insert(sysFolder) > 0) {
			return JSON.toJSONString(new ResultBean(1, "添加成功"));
		} else {
			return JSON.toJSONString(new ResultBean(1, "添加失败"));
		}
	}

	@RequestMapping("/emailAddAccountDo")
	@ResponseBody
	public String emailAddAccountDo(HttpServletRequest request, Model model) {
		String email = CommonUtils.getString(request.getParameter("email"));
		String mailType = CommonUtils.getString(request.getParameter("mailType"));
		String password = CommonUtils.getString(request.getParameter("password"));
		String protocol = CommonUtils.getString(request.getParameter("protocol"));
		String reAddress = CommonUtils.getString(request.getParameter("reAddress"));
		String rePort = CommonUtils.getString(request.getParameter("rePort"));
		String sendAddress = CommonUtils.getString(request.getParameter("sendAddress"));
		String sendPort = CommonUtils.getString(request.getParameter("sendPort"));
		String ssl = CommonUtils.getString(request.getParameter("ssl"));
		String submit = CommonUtils.getString(request.getParameter("submit"));
		if (StringUtils.isBlank(email)) {
			ResultBean result = new ResultBean(0, "没有邮箱类型");
			return JSON.toJSONString(result);
		}

		boolean isSSL = true;
		if (!ssl.equals("on")) {
			isSSL = false;
		}
		boolean isSubmit = true;
		if (!submit.equals("on")) {
			isSubmit = false;
		}
		boolean isPOP3 = false;
		if (!protocol.equals("imap")) {
			isPOP3 = true;
		}

		long userId = this.getUserId();
		List<SysEmailAccount> hasEmail = emailService.list(userId);
		boolean flag = false;
		for (int i = 0; i < hasEmail.size(); i++) {
			if (hasEmail.get(i).getAccount().trim().equals(email)) {
				flag = true;
				break;
			}
		}
		if (flag) {
			return JSON.toJSONString(new ResultBean(0, "已经存在此邮箱"));
		}

		MailBean re = null;
		MailBean send = null;
		if (mailType.trim().equals("1")) {
			re = MailProperties.getQQMailBean(isPOP3, isSSL);
			send = MailProperties.getQQMailBean(isSSL);
			re.setHost(reAddress);
			re.setPort(rePort);
			re.setSocketFactoryPort(rePort);
			send.setHost(sendAddress);
			send.setPort(sendPort);
			send.setSocketFactoryPort(sendPort);

		} else {
			switch (mailType.trim()) {
			
			case "QQ":
				re = MailProperties.getQQMailBean(isPOP3, isSSL);
				send = MailProperties.getQQMailBean(isSSL);
				break;
			case "aliyun":
				re = MailProperties.getALIMailBean(isPOP3, isSSL);
				send = MailProperties.getALIMailBean(isSSL);
				break;
			case "yahoo":
				re = MailProperties.getYaHooMailBean(isPOP3, isSSL);
				send = MailProperties.getYaHooMailBean(isSSL);
				break;
			case "exQQ":
				re = MailProperties.getEXQQMailBean(isPOP3, isSSL);
				send = MailProperties.getEXQQMailBean(isSSL);
				break;
			case "gmail":
				re = MailProperties.getGoogleMailBean(isPOP3, isSSL);
				send = MailProperties.getGoogleMailBean(isSSL);
				break;
			}
		}
		re.setAccount(email);
		re.setPassword(password);
		MailConnect mailConnect = new MailConnect(re);
		try {
			mailConnect.checkProperties();
		} catch (Exception e) {
			return JSON.toJSONString(new ResultBean(0, "检测失败"));
		}
		if (mailConnect.getState() == 0) {
			SysEmailAccount sysEmailAccount = new SysEmailAccount();
			sysEmailAccount.setUserId(userId);
			sysEmailAccount.setAccount(email);
			sysEmailAccount.setPassword(password);
			sysEmailAccount.setMailType(mailType);

			if (isSSL) {
				sysEmailAccount.setIsSsl("true");
			} else {
				sysEmailAccount.setIsSsl("false");
			}
			if (isSubmit) {
				sysEmailAccount.setIsSubmit("true");
			} else {
				sysEmailAccount.setIsSubmit("false");
			}
			sysEmailAccount.setProtocol(protocol);
			sysEmailAccount.setHost(re.getHost());
			sysEmailAccount.setPort(re.getPort());
			sysEmailAccount.setSendHost(send.getHost());
			sysEmailAccount.setSendPort(send.getPort());

			int temp = emailService.insert(sysEmailAccount);
			if (temp > 0) {
				return JSON.toJSONString(new ResultBean(1, "添加成功"));
			} else {
				return JSON.toJSONString(new ResultBean(0, "添加失败"));
			}
		} else {
			return JSON.toJSONString(new ResultBean(0, mailConnect.getErrorMsg()));
		}
	}

	@RequestMapping("/emailEditDo")
	@ResponseBody
	public String emailEditDo(HttpServletRequest request, Model model) {
		String id = "";
		int idTemp = 0;
		long userId = this.getUserId();
		SysEmailAccount temp = null;
		try {
			id = CommonUtils.getString(request.getParameter("id"));
			idTemp = Integer.parseInt(id);
			temp = emailService.get(idTemp, userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (temp == null) {
			return JSON.toJSONString(new ResultBean(0, "记录不存在"));
		}

		String email = CommonUtils.getString(request.getParameter("email"));
		String mailType = CommonUtils.getString(request.getParameter("mailType"));
		String password = CommonUtils.getString(request.getParameter("password"));
		String protocol = CommonUtils.getString(request.getParameter("protocol"));
		String reAddress = CommonUtils.getString(request.getParameter("reAddress"));
		String rePort = CommonUtils.getString(request.getParameter("rePort"));
		String sendAddress = CommonUtils.getString(request.getParameter("sendAddress"));
		String sendPort = CommonUtils.getString(request.getParameter("sendPort"));
		String ssl = CommonUtils.getString(request.getParameter("ssl"));
		String submit = CommonUtils.getString(request.getParameter("submit"));
		if (StringUtils.isBlank(email)) {
			ResultBean result = new ResultBean(0, "没有邮箱类型");
			return JSON.toJSONString(result);
		}

		boolean isSSL = true;
		if (!ssl.equals("on")) {
			isSSL = false;
		}
		boolean isSubmit = true;
		if (!submit.equals("on")) {
			isSubmit = false;
		}
		boolean isPOP3 = false;
		if (!protocol.equals("imap")) {
			isPOP3 = true;
		}

		MailBean re = null;
		MailBean send = null;
		if (mailType.trim().equals("1")) {
			re = MailProperties.getQQMailBean(isPOP3, isSSL);
			send = MailProperties.getQQMailBean(isSSL);
			re.setHost(reAddress);
			re.setPort(rePort);
			re.setSocketFactoryPort(rePort);
			send.setHost(sendAddress);
			send.setPort(sendPort);
			send.setSocketFactoryPort(sendPort);

		} else {
			switch (mailType.trim()) {
			
			case "QQ":
				re = MailProperties.getQQMailBean(isPOP3, isSSL);
				send = MailProperties.getQQMailBean(isSSL);
				break;
			case "aliyun":
				re = MailProperties.getALIMailBean(isPOP3, isSSL);
				send = MailProperties.getALIMailBean(isSSL);
				break;
			case "yahoo":
				re = MailProperties.getYaHooMailBean(isPOP3, isSSL);
				send = MailProperties.getYaHooMailBean(isSSL);
				break;
			case "exQQ":
				re = MailProperties.getEXQQMailBean(isPOP3, isSSL);
				send = MailProperties.getEXQQMailBean(isSSL);
				break;
			case "gmail":
				re = MailProperties.getGoogleMailBean(isPOP3, isSSL);
				send = MailProperties.getGoogleMailBean(isSSL);
				break;
			}
		}
		re.setAccount(email);
		re.setPassword(password);
		MailConnect mailConnect = new MailConnect(re);
		try {
			mailConnect.checkProperties();
		} catch (Exception e) {
			return JSON.toJSONString(new ResultBean(0, "检测失败"));
		}
		if (mailConnect.getState() == 0) {

			temp.setUserId(userId);
			temp.setAccount(email);
			temp.setPassword(password);
			temp.setMailType(mailType);

			if (isSSL) {
				temp.setIsSsl("true");
			} else {
				temp.setIsSsl("false");
			}
			if (isSubmit) {
				temp.setIsSubmit("true");
			} else {
				temp.setIsSubmit("false");
			}
			temp.setProtocol(protocol);
			temp.setHost(re.getHost());
			temp.setPort(re.getPort());
			temp.setSendHost(send.getHost());
			temp.setSendPort(send.getPort());

			long result = emailService.update(temp);
			if (result > 0) {
				return JSON.toJSONString(new ResultBean(1, "修改成功"));
			} else {
				return JSON.toJSONString(new ResultBean(0, "添加失败"));
			}
		} else {
			return JSON.toJSONString(new ResultBean(0, mailConnect.getErrorMsg()));
		}
	}

	@RequestMapping("/labelEditDo")
	@ResponseBody
	public String labelEditDo(HttpServletRequest request, Model model) {
		String id = "";
		int idTemp = 0;
		long userId = this.getUserId();
		String name = CommonUtils.getString(request.getParameter("name"));
		SysLabel temp = null;
		try {
			id = CommonUtils.getString(request.getParameter("id"));
			idTemp = Integer.parseInt(id);
			temp = labelService.get(idTemp, userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (temp == null) {
			return JSON.toJSONString(new ResultBean(0, "记录不存在"));
		}
		if (StringUtils.isBlank(name)) {
			return JSON.toJSONString(new ResultBean(0, "没有标签名称"));
		}
		temp.setName(name);
		temp.setUserId((long) this.getUserId());
		if (labelService.update(temp) > 0) {
			return JSON.toJSONString(new ResultBean(1, "修改成功"));
		} else {
			return JSON.toJSONString(new ResultBean(1, "修改失败"));
		}
	}

	@RequestMapping("/folderEditDo")
	@ResponseBody
	public String folderEditDo(HttpServletRequest request, Model model) {
		String id = "";
		int idTemp = 0;
		long userId = this.getUserId();
		String name = CommonUtils.getString(request.getParameter("name"));
		SysFolder temp = null;
		try {
			id = CommonUtils.getString(request.getParameter("id"));
			idTemp = Integer.parseInt(id);
			temp = folderService.get(idTemp, userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (temp == null) {
			return JSON.toJSONString(new ResultBean(0, "记录不存在"));
		}
		if (StringUtils.isBlank(name)) {
			return JSON.toJSONString(new ResultBean(0, "没有文件夹名"));
		}
		temp.setName(name);
		temp.setUserId((long) this.getUserId());
		if (folderService.update(temp) > 0) {
			return JSON.toJSONString(new ResultBean(1, "修改成功"));
		} else {
			return JSON.toJSONString(new ResultBean(1, "修改失败"));
		}
	}

	@RequestMapping("/emailDeleteAccount")
	@ResponseBody
	public String emailDeleteAccount(HttpServletRequest request, Model model) {
		try {
			SysEmailAccount sysEmailAccount = new SysEmailAccount();
			sysEmailAccount.setUserId(this.getUserId());
			sysEmailAccount.setId(Long.parseLong(request.getParameter("id")));
			int i = emailService.delete(sysEmailAccount);
			if (i > 0) {
				return JSON.toJSONString(new ResultBean(1, "删除成功"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSON.toJSONString(new ResultBean(1, "删除失败"));
	}

	@RequestMapping("/labelDel")
	@ResponseBody
	public String labelDel(HttpServletRequest request, Model model) {
		try {
			String id = CommonUtils.getString(request.getParameter("id"));
			int idTemp = Integer.parseInt(id);
			long i = labelService.delete(idTemp, this.getUserId());
			if (i > 0) {
				return JSON.toJSONString(new ResultBean(1, "删除成功"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSON.toJSONString(new ResultBean(1, "删除失败"));
	}

	@RequestMapping("/folderDel")
	@ResponseBody
	public String folderDel(HttpServletRequest request, Model model) {
		try {
			String id = CommonUtils.getString(request.getParameter("id"));
			int idTemp = Integer.parseInt(id);
			long i = folderService.delete(idTemp, this.getUserId());
			if (i > 0) {
				return JSON.toJSONString(new ResultBean(1, "删除成功"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSON.toJSONString(new ResultBean(1, "删除失败"));
	}

	private SysMessageInbox toSysMessageInbox(MailContent content, long userId, long mailId, String folder,
											  boolean isDefaultFolder, long folderId, boolean saveAttachment, String path) {
		SysMessageInbox temp = new SysMessageInbox();
		temp.setUserId(userId);
		temp.setMailId(mailId);
		temp.setFolder(folder);
		temp.setFolderId(folderId);
		temp.setMessageId(content.getMessageId());
		temp.setSubject(content.getSubject());
		temp.setBodyText(content.getBodyText());
		temp.setSentDate(CommonUtils.getDateStr(content.getSentDate()));
		temp.setSentDateTime(content.getSentDate()==null?"":content.getSentDate().getTime() + "");
		temp.setSize((long) content.getSize());
		temp.setMailFrom(content.getFrom());
		temp.setMailAddress(content.getMailAddressStr());
		temp.setMailCopyto(content.getCopyToStr());
		temp.setMailBCopyto(content.getBCopyToStr());
		if (content.isHasAttachMent()) {
			temp.setHasAttachment("true");
		} else {
			temp.setHasAttachment("false");
		}
		if (ObjectUtil.isNotEmpty(temp.getAttachment()) && saveAttachment) {
			content.saveAttachment(path + "\\" + EmailController.saveFolder + "\\" + userId + "\\" + mailId + "\\");

			ArrayList<String> fileNames = content.getFileNames();

			String[] fileUrls = new String[fileNames.size()];
			for (int i = 0; i < fileNames.size(); i++) {
				fileUrls[i] = EmailController.saveURL + "/" + EmailController.saveFolder + "/" + userId + "/" + mailId
						+ "/" + fileNames.get(i);
			}
			temp.setAttachment(StringUtils.join(fileUrls, ","));
		}
		if (content.isNew()) {
			temp.setHasRead("false");
		} else {
			temp.setHasRead("true");
		}
		if (isDefaultFolder) {
			temp.setIsDefaultFolder("true");
		} else {
			temp.setIsDefaultFolder("false");
		}
		temp.setHasReply("false");
		temp.setLabel("");
		temp.setSource();
		temp.setState((long) 0);
		return temp;
	}

	private void printAllFolders(Store store) throws MessagingException {
		Folder[] folders = store.getDefaultFolder().list("*");
		for (Folder f : folders) {
			System.out.printf("原始名称: %-15s → 显示名称: %s%n",
					f.getFullName(),
					f.getName());

			// 递归打印子文件夹
			if ((f.getType() & Folder.HOLDS_FOLDERS) != 0) {
				printSubFolders(f, "  ");
			}
		}
	}

	private void printSubFolders(Folder parent, String indent) throws MessagingException {
		// 必须打开才能获取子目录（从第二层开始）
		if (!parent.isOpen()) {
			parent.open(Folder.READ_ONLY);
		}
		for (Folder f : parent.list()) {
			System.out.printf("%s└─ 原始: %-15s → 显示: %s%n",
					indent, f.getFullName(), f.getName());
		}
	}

}
